<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>科技蛇 - Tech Snake</title>
    
    <link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;500;700&display=swap" rel="stylesheet">
    <style>
      /* 基础样式重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

:root {
  --primary: #00f7ff;
  --primary-dark: #00b3b9;
  --primary-glow: rgba(0, 247, 255, 0.5);
  --accent: #ff0066;
  --accent-glow: rgba(255, 0, 102, 0.5);
  --background: #000814;
  --surface: #0a1128;
  --surface-light: #121a2c;
  --text: #e0fbfc;
  --text-secondary: #91a8d0;
  --success: #00ff88;
  --warning: #ffb703;
  --danger: #FF3A44;
}

@font-face {
  font-family: 'CyberPunk';
  src: url('../fonts/cyber.woff2') format('woff2');
  font-weight: normal;
  font-style: normal;
}

html, body {
  height: 100%;
  width: 100%;
  overflow-x: hidden;
  font-family: 'Orbitron', sans-serif;
  background: var(--background);
  color: var(--text);
  line-height: 1.6;
}

body {
  background: radial-gradient(circle at 50% 50%, #071425, #000510);
  background-attachment: fixed;
}

/* 游戏容器 */
.game-container {
  max-width: 1200px;
  margin: 20px auto;
  background: var(--surface);
  border: 2px solid var(--primary);
  border-radius: 10px;
  box-shadow: 0 0 25px var(--primary-glow), inset 0 0 15px var(--primary-glow);
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding: 20px;
}

.game-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, transparent, var(--primary), transparent);
  z-index: 1;
  animation: headerGlow 3s ease-in-out infinite;
}

@keyframes headerGlow {
  0%, 100% { opacity: 0.3; transform: scaleX(0.8); }
  50% { opacity: 1; transform: scaleX(1); }
}

/* 游戏标题 */
.game-header {
  display: flex;
  flex-direction: column;
  gap: 15px;
  position: relative;
}

.title-container {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.game-title {
  text-align: center;
  font-size: 3rem;
  font-weight: 700;
  background: linear-gradient(90deg, var(--primary), #80ffea, var(--accent));
  background-clip: text;
  -webkit-background-clip: text;
  color: transparent;
  text-transform: uppercase;
  letter-spacing: 2px;
  margin: 10px 0;
  position: relative;
  text-shadow: 0 0 10px var(--primary-glow);
}

.game-title span {
  display: block;
  font-size: 1rem;
  letter-spacing: 8px;
  opacity: 0.7;
}

/* 反应堆装饰 */
.reactor {
  position: absolute;
  right: 50px;
  top: 50%;
  transform: translateY(-50%);
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.reactor-core {
  width: 20px;
  height: 20px;
  background: var(--primary);
  border-radius: 50%;
  box-shadow: 0 0 15px var(--primary);
  animation: pulse 2s infinite alternate;
}

.reactor-ring {
  position: absolute;
  border: 2px solid transparent;
  border-radius: 50%;
}

.ring1 {
  width: 30px;
  height: 30px;
  border-top-color: var(--primary);
  border-bottom-color: var(--primary);
  animation: spin 3s linear infinite;
}

.ring2 {
  width: 45px;
  height: 45px;
  border-left-color: var(--primary);
  border-right-color: var(--primary);
  animation: spin 4s linear infinite reverse;
}

.ring3 {
  width: 60px;
  height: 60px;
  border-top-color: var(--primary);
  border-right-color: var(--primary);
  animation: spin 5s linear infinite;
}

@keyframes pulse {
  0%, 100% { transform: scale(0.8); opacity: 0.8; }
  50% { transform: scale(1.1); opacity: 1; }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 游戏统计信息 */
.game-stats {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  gap: 10px;
  background: rgba(10, 17, 40, 0.7);
  border: 1px solid var(--primary-dark);
  border-radius: 8px;
  padding: 10px;
  box-shadow: 0 0 10px rgba(0, 247, 255, 0.2), inset 0 0 5px rgba(0, 247, 255, 0.1);
}

.stat-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 80px;
  padding: 5px 10px;
  border-left: 2px solid var(--primary);
  position: relative;
  overflow: hidden;
}

.stat-box::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 1px;
  background: linear-gradient(90deg, transparent, var(--primary), transparent);
}

.stat-label {
  font-size: 0.8rem;
  color: var(--text-secondary);
  text-transform: uppercase;
  letter-spacing: 1px;
}

.stat-value {
  font-size: 1.5rem;
  font-weight: 700;
  color: var(--primary);
  text-shadow: 0 0 5px var(--primary-glow);
}

.ai-score, .ai-length {
  display: none; /* 默认隐藏AI相关信息 */
}

/* 特效容器 */
.effects-container {
  margin-top: 10px;
  border: 1px solid var(--primary-dark);
  border-radius: 8px;
  background: rgba(10, 17, 40, 0.5);
  padding: 10px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.effects-title {
  font-size: 0.9rem;
  text-transform: uppercase;
  color: var(--primary);
  border-bottom: 1px solid var(--primary-dark);
  padding-bottom: 5px;
  text-shadow: 0 0 5px var(--primary-glow);
  letter-spacing: 1px;
}

.effects-items {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  gap: 10px;
}

.effect {
  padding: 8px 12px;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 5px;
  border-left: 3px solid;
  font-size: 0.85rem;
  display: flex;
  align-items: center;
  animation: fadeIn 0.3s;
  transition: all 0.3s;
  box-shadow: 0 0 8px currentColor;
}

.effect:hover {
  transform: translateY(-3px);
  box-shadow: 0 0 15px currentColor;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-10px); }
  to { opacity: 1; transform: translateY(0); }
}

/* 游戏区域 */
.game-field {
  position: relative;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.canvas-container {
  position: relative;
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
}

#gameCanvas {
  display: block;
  width: 100%;
  background-color: var(--background);
  image-rendering: pixelated;
}

.grid-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image:
    linear-gradient(rgba(0, 247, 255, 0.05) 1px, transparent 1px),
    linear-gradient(90deg, rgba(0, 247, 255, 0.05) 1px, transparent 1px);
  background-size: 20px 20px;
  pointer-events: none;
}

.scanline {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 247, 255, 0.1) 50%, rgba(0, 0, 0, 0) 100%);
  opacity: 0.2;
  animation: scan 8s linear infinite;
  pointer-events: none;
}

@keyframes scan {
  0% { transform: translateY(-100%); }
  100% { transform: translateY(100%); }
}

/* 控制面板 */
.game-controls {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.control-panel {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  justify-content: center;
  background: rgba(10, 17, 40, 0.5);
  border: 1px solid var(--primary-dark);
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
}

.control-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.control-group label {
  font-size: 0.9rem;
  text-transform: uppercase;
  color: var(--text-secondary);
  letter-spacing: 1px;
}

.slider-container {
  position: relative;
  width: 200px;
}

input[type="range"] {
  -webkit-appearance: none;
  width: 100%;
  height: 8px;
  background: linear-gradient(90deg, var(--primary-dark), var(--primary));
  border-radius: 4px;
  outline: none;
}

input[type="range"]::-webkit-slider-thumb {
  -webkit-appearance: none;
  width: 18px;
  height: 18px;
  background: var(--text);
  border-radius: 50%;
  cursor: pointer;
  box-shadow: 0 0 8px var(--primary);
  transition: all 0.2s;
}

input[type="range"]::-webkit-slider-thumb:hover {
  background: var(--primary);
  box-shadow: 0 0 12px var(--primary);
}

.slider-value {
  position: absolute;
  top: -25px;
  left: 50%;
  transform: translateX(-50%);
  background: var(--primary);
  color: var(--background);
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: bold;
  width: 25px;
  text-align: center;
}

.slider-value::after {
  content: '';
  position: absolute;
  bottom: -5px;
  left: 50%;
  transform: translateX(-50%);
  width: 0;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 5px solid var(--primary);
}

.difficulty-select {
  background: var(--surface-light);
  color: var(--text);
  border: 2px solid var(--primary-dark);
  border-radius: 4px;
  padding: 8px 15px;
  font-family: 'Orbitron', sans-serif;
  font-size: 0.9rem;
  cursor: pointer;
  outline: none;
  transition: border-color 0.3s, box-shadow 0.3s;
  width: 200px;
}

.difficulty-select:focus {
  border-color: var(--primary);
  box-shadow: 0 0 8px var(--primary-glow);
}

.difficulty-select option {
  background: var(--surface);
  color: var(--text);
}

/* 按钮样式 */
.button-group {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 10px;
  padding: 10px 0;
}

.cyber-button {
  position: relative;
  background: transparent;
  color: var(--primary);
  font-family: 'Orbitron', sans-serif;
  font-size: 1rem;
  padding: 10px 20px;
  border: 2px solid var(--primary);
  border-radius: 0;
  cursor: pointer;
  outline: none;
  overflow: hidden;
  transition: all 0.3s;
  min-width: 120px;
  text-transform: uppercase;
  box-shadow: 0 0 5px var(--primary-glow);
  clip-path: polygon(0 10%, 10% 0, 90% 0, 100% 10%, 100% 90%, 90% 100%, 10% 100%, 0 90%);
}

.cyber-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, var(--primary-glow), transparent);
  transition: all 0.6s;
}

.cyber-button:hover {
  color: var(--background);
  background: var(--primary);
  box-shadow: 0 0 15px var(--primary);
  transform: translateY(-2px);
}

.cyber-button:hover::before {
  left: 100%;
}

.button-content {
  position: relative;
  z-index: 1;
}

.button-glitch {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: var(--primary);
  z-index: 0;
  opacity: 0;
  transition: opacity 0.2s;
  mix-blend-mode: screen;
}

.cyber-button:active .button-glitch {
  opacity: 0.3;
  animation: glitch 0.3s steps(2) forwards;
}

@keyframes glitch {
  0% { transform: translate(0); }
  20% { transform: translate(-5px, 5px); }
  40% { transform: translate(-5px, -5px); }
  60% { transform: translate(5px, 5px); }
  80% { transform: translate(5px, -5px); }
  100% { transform: translate(0); }
}

.toggle-button {
  background: transparent;
  color: var(--text-secondary);
  border-color: var(--text-secondary);
  box-shadow: none;
}

.toggle-button.active {
  background: var(--primary);
  color: var(--background);
  border-color: var(--primary);
  box-shadow: 0 0 15px var(--primary-glow);
}

#startBtn {
  background: var(--success);
  color: var(--background);
  border-color: var(--success);
  box-shadow: 0 0 15px rgba(0, 255, 136, 0.5);
}

#pauseBtn {
  display: none;
}

/* 移动设备控制 */
.mobile-controls {
  display: none;
  position: relative;
  width: 100%;
  margin: 15px 0;
  background: rgba(10, 17, 40, 0.3);
  border-radius: 10px;
  padding: 15px;
}

.controls-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 400px;
  margin: 0 auto;
}

.d-pad {
  display: grid;
  grid-template-areas:
    ". up ."
    "left . right"
    ". down .";
  gap: 5px;
  width: 150px;
  height: 150px;
}

.direction-btn {
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0, 247, 255, 0.1);
  color: var(--primary);
  border: 1px solid var(--primary);
  border-radius: 8px;
  width: 45px;
  height: 45px;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 0 5px var(--primary-glow);
}

.direction-btn svg {
  width: 24px;
  height: 24px;
  fill: currentColor;
}

.direction-btn:active {
  background: var(--primary);
  color: var(--background);
  transform: scale(0.9);
}

.up-btn { grid-area: up; }
.left-btn { grid-area: left; }
.right-btn { grid-area: right; }
.down-btn { grid-area: down; }

/* 加速按钮样式 */
.action-buttons {
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 10px;
}

.boost-btn {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  background: radial-gradient(circle at 30% 30%, var(--accent), #800033);
  border: 2px solid var(--accent);
  color: var(--text);
  font-family: 'Orbitron', sans-serif;
  font-size: 0.9rem;
  font-weight: bold;
  text-transform: uppercase;
  cursor: pointer;
  box-shadow: 0 0 15px var(--accent-glow);
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.boost-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: radial-gradient(circle at center, rgba(255,255,255,0.2) 0%, transparent 70%);
  pointer-events: none;
}

.boost-btn:active, .boost-btn.active {
  transform: scale(0.9);
  box-shadow: 0 0 25px var(--accent);
}

.boost-btn.active {
  background: radial-gradient(circle at 30% 30%, #ff3881, var(--accent));
  animation: boostPulse 0.5s infinite alternate;
}

@keyframes boostPulse {
  from { box-shadow: 0 0 15px var(--accent-glow); }
  to { box-shadow: 0 0 30px var(--accent), 0 0 40px var(--accent-glow); }
}

.boost-btn::after {
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  border: 2px solid var(--accent);
  animation: pulseRing 2s infinite;
  opacity: 0;
}

.boost-btn.active::after {
  opacity: 0.8;
  animation: pulseRing 1s infinite;
}

@keyframes pulseRing {
  0% { transform: scale(0.8); opacity: 0; }
  50% { opacity: 0.5; }
  100% { transform: scale(1.4); opacity: 0; }
}

/* 食物指南 */
.food-guide {
  background: rgba(10, 17, 40, 0.5);
  border: 1px solid var(--primary-dark);
  border-radius: 8px;
  padding: 15px;
  margin-top: 10px;
}

.guide-title {
  text-align: center;
  color: var(--primary);
  font-size: 1.2rem;
  text-transform: uppercase;
  letter-spacing: 2px;
  margin-bottom: 15px;
  position: relative;
  text-shadow: 0 0 5px var(--primary-glow);
}

.guide-title::after {
  content: '';
  position: absolute;
  bottom: -5px;
  left: 50%;
  transform: translateX(-50%);
  width: 50px;
  height: 2px;
  background: var(--primary);
  box-shadow: 0 0 5px var(--primary);
}

.food-items {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  gap: 10px;
}

.food-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px;
  border-radius: 5px;
  background: rgba(0, 0, 0, 0.3);
  transition: all 0.3s;
}

.food-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2);
}

.food-icon {
  width: 20px;
  height: 20px;
  border-radius: 50%;
}

.food-icon.normal {
  background: radial-gradient(circle at 30% 30%, #4CAF50, #388E3C);
  box-shadow: 0 0 10px rgba(76, 175, 80, 0.5);
}

.food-icon.speedBoost {
  background: radial-gradient(circle at 30% 30%, #FFC107, #FF9800);
  box-shadow: 0 0 10px rgba(255, 193, 7, 0.5);
}

.food-icon.doubleScore {
  background: radial-gradient(circle at 30% 30%, #9C27B0, #7B1FA2);
  box-shadow: 0 0 10px rgba(156, 39, 176, 0.5);
}

.food-icon.shield {
  background: radial-gradient(circle at 30% 30%, #2196F3, #1976D2);
  box-shadow: 0 0 10px rgba(33, 150, 243, 0.5);
}

.food-info {
  display: flex;
  flex-direction: column;
}

.food-name {
  font-size: 0.9rem;
  font-weight: 500;
  color: var(--text);
}

.food-desc {
  font-size: 0.75rem;
  color: var(--text-secondary);
}

/* 模态框 */
.modal {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(5px);
  z-index: 1000;
  align-items: center;
  justify-content: center;
}

.modal-content {
  position: relative;
  background: var(--surface);
  border: 2px solid var(--primary);
  border-radius: 10px;
  padding: 25px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 0 30px var(--primary-glow), inset 0 0 15px rgba(0, 0, 0, 0.5);
  overflow: hidden;
  animation: modalAppear 0.5s;
}

@keyframes modalAppear {
  from { transform: scale(0.9); opacity: 0; }
  to { transform: scale(1); opacity: 1; }
}

.particles {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: -1;
}

.modal-header {
  text-align: center;
  margin-bottom: 20px;
  position: relative;
}

.mode-badge {
  display: inline-block;
  padding: 5px 10px;
  margin-bottom: 10px;
  font-size: 0.8rem;
  border-radius: 5px;
  background: var(--primary);
  color: var(--background);
  text-transform: uppercase;
  letter-spacing: 1px;
}

.modal-title {
  font-size: 2rem;
  font-weight: 700;
  color: var(--primary);
  text-transform: uppercase;
  letter-spacing: 2px;
  text-shadow: 0 0 10px var(--primary-glow);
}

.score-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  margin: 20px 0;
}

.score-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 5px;
}

.score-label {
  font-size: 0.85rem;
  color: var(--text-secondary);
  text-transform: uppercase;
}

.score-value {
  font-size: 1.5rem;
  font-weight: 700;
  color: var(--primary);
  text-shadow: 0 0 5px var(--primary-glow);
}

.modal-buttons {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
  flex-wrap: wrap;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .game-container {
    margin: 10px;
    padding: 10px;
  }
  
  .game-title {
    font-size: 2rem;
  }
  
  .reactor {
    width: 40px;
    height: 40px;
    right: 20px;
  }
  
  .score-container {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .control-panel {
    flex-direction: column;
  }
  
  .mobile-controls {
    display: block;
  }
  
  .controls-wrapper {
    max-width: 320px;
  }
  
  .d-pad {
    width: 130px;
    height: 130px;
  }
  
  .direction-btn {
    width: 40px;
    height: 40px;
  }
  
  .boost-btn {
    width: 60px;
    height: 60px;
    font-size: 0.8rem;
  }
}

@media (max-width: 480px) {
  .game-title {
    font-size: 1.5rem;
  }
  
  .stat-box {
    min-width: 70px;
  }
  
  .stat-value {
    font-size: 1.2rem;
  }
  
  .food-items {
    flex-direction: column;
  }
  
  .controls-wrapper {
    max-width: 280px;
  }
  
  .d-pad {
    width: 120px;
    height: 120px;
  }
  
  .direction-btn {
    width: 35px;
    height: 35px;
  }
  
  .direction-btn svg {
    width: 18px;
    height: 18px;
  }
  
  .boost-btn {
    width: 50px;
    height: 50px;
    font-size: 0.7rem;
  }
}

/* 动画效果 */
@keyframes moveGradient {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}

@keyframes glow {
  0%, 100% { box-shadow: 0 0 10px var(--primary-glow); }
  50% { box-shadow: 0 0 20px var(--primary-glow), 0 0 30px var(--primary-glow); }
}

/* 分数弹出动画 */
.score-pop {
  position: absolute;
  color: var(--primary);
  font-size: 1.2rem;
  font-weight: bold;
  text-shadow: 0 0 5px var(--primary);
  z-index: 100;
  pointer-events: none;
  animation: scorePop 1s forwards;
}

@keyframes scorePop {
  0% { transform: translateY(0) scale(0.5); opacity: 0; }
  50% { transform: translateY(-20px) scale(1.5); opacity: 1; }
  100% { transform: translateY(-40px) scale(1); opacity: 0; }
}

/* 屏幕抖动效果 */
.shake {
  animation: shake 0.5s cubic-bezier(.36,.07,.19,.97) both;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
  20%, 40%, 60%, 80% { transform: translateX(5px); }
}

/* 暂停效果 */
.canvas-container.paused::after {
  content: '已暂停';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--primary);
  font-size: 2rem;
  text-transform: uppercase;
  letter-spacing: 5px;
  z-index: 10;
  backdrop-filter: blur(3px);
  animation: pauseGlow 2s infinite alternate;
}

@keyframes pauseGlow {
  0% { text-shadow: 0 0 5px var(--primary-glow); }
  100% { text-shadow: 0 0 20px var(--primary), 0 0 30px var(--primary); }
}

/* 故障效果 */
.canvas-container.glitch {
  animation: glitchEffect 0.5s steps(2) forwards;
}

@keyframes glitchEffect {
  0% { transform: translate(0); filter: hue-rotate(0deg); }
  10% { transform: translate(-5px, 5px); filter: hue-rotate(90deg); }
  20% { transform: translate(-5px, -5px); filter: hue-rotate(180deg); }
  30% { transform: translate(5px, 5px); filter: hue-rotate(270deg); }
  40% { transform: translate(5px, -5px); filter: hue-rotate(360deg); }
  50% { transform: translate(0); filter: hue-rotate(0deg); }
  60% { transform: translate(-3px, 3px); filter: saturate(2); }
  70% { transform: translate(3px, -3px); filter: saturate(0.5); }
  80% { transform: translate(0); filter: hue-rotate(0deg); }
  90% { transform: translate(-2px, 2px); filter: brightness(1.2); }
  100% { transform: translate(0); filter: none; }
}

/* 模态框粒子 */
.modal-particle {
  position: absolute;
  background-color: var(--primary);
  border-radius: 50%;
  pointer-events: none;
  animation: floatParticle 4s infinite alternate;
}

@keyframes floatParticle {
  0% { transform: translate(0, 0) rotate(0deg); opacity: 0.3; }
  50% { opacity: 0.8; }
  100% { transform: translate(20px, -20px) rotate(360deg); opacity: 0.3; }
}

/* 按钮悬停效果增强 */
.cyber-button:hover {
  animation: buttonHover 2s infinite;
}

@keyframes buttonHover {
  0%, 100% { box-shadow: 0 0 15px var(--primary); }
  50% { box-shadow: 0 0 25px var(--primary), 0 0 35px var(--primary-glow); }
}

/* 活动的食物效果 */
@keyframes foodPulse {
  0%, 100% { transform: scale(0.9); opacity: 0.8; }
  50% { transform: scale(1.1); opacity: 1; box-shadow: 0 0 20px currentColor; }
}

.food-icon {
  animation: foodPulse 2s infinite;
}

/* 添加额外的反应堆风格 */
.reactor-core::after {
  content: '';
  position: absolute;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: radial-gradient(circle, rgba(0,247,255,0.1) 0%, rgba(0,247,255,0) 70%);
  animation: reactorPulse 3s infinite;
}

@keyframes reactorPulse {
  0%, 100% { transform: scale(1); opacity: 0; }
  50% { transform: scale(2); opacity: 0.5; }
}

/* 游戏介绍区域样式 */
.game-instructions {
  background: rgba(10, 17, 40, 0.7);
  border: 1px solid var(--primary-dark);
  border-radius: 8px;
  padding: 15px;
  margin-top: 15px;
  box-shadow: 0 0 15px rgba(0, 247, 255, 0.2), inset 0 0 8px rgba(0, 247, 255, 0.1);
}

.instructions-title {
  font-size: 1.3rem;
  text-transform: uppercase;
  color: var(--primary);
  text-align: center;
  margin-bottom: 15px;
  text-shadow: 0 0 5px var(--primary-glow);
  letter-spacing: 2px;
  border-bottom: 1px solid var(--primary-dark);
  padding-bottom: 8px;
  position: relative;
}

.instructions-title::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 50%;
  transform: translateX(-50%);
  width: 100px;
  height: 2px;
  background: linear-gradient(90deg, transparent, var(--primary), transparent);
  animation: instructionGlow 3s ease-in-out infinite;
}

@keyframes instructionGlow {
  0%, 100% { width: 80px; opacity: 0.5; }
  50% { width: 150px; opacity: 1; }
}

.instructions-content {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  gap: 20px;
}

.instruction-section {
  flex: 1;
  min-width: 250px;
  padding: 10px;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 5px;
  border-left: 3px solid var(--primary);
}

.instruction-section h4 {
  color: var(--primary);
  margin-bottom: 10px;
  font-size: 1rem;
  letter-spacing: 1px;
}

.instruction-section ul {
  list-style-type: none;
  padding-left: 5px;
}

.instruction-section li {
  margin-bottom: 8px;
  font-size: 0.9rem;
  position: relative;
  padding-left: 15px;
  line-height: 1.4;
}

.instruction-section li::before {
  content: '▶';
  color: var(--primary);
  position: absolute;
  left: 0;
  font-size: 0.7rem;
}

.key-highlight {
  background: rgba(0, 247, 255, 0.1);
  border: 1px solid var(--primary-dark);
  padding: 2px 5px;
  border-radius: 3px;
  font-family: monospace;
  color: var(--primary);
  font-weight: 500;
}

.mode-highlight {
  color: var(--accent);
  font-weight: 500;
}

/* 加载屏幕 */
.loading-screen {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: var(--background);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: opacity 0.5s ease;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.loading-title {
  font-size: 2rem;
  color: var(--primary);
  text-transform: uppercase;
  letter-spacing: 3px;
  text-shadow: 0 0 10px var(--primary-glow);
  animation: pulseText 1.5s infinite alternate;
}

@keyframes pulseText {
  from { opacity: 0.7; text-shadow: 0 0 5px var(--primary-glow); }
  to { opacity: 1; text-shadow: 0 0 15px var(--primary-glow), 0 0 30px var(--primary-glow); }
}

.loading-spinner {
  width: 60px;
  height: 60px;
  border: 3px solid transparent;
  border-top-color: var(--primary);
  border-right-color: var(--accent);
  border-radius: 50%;
  animation: loadingSpin 1s linear infinite;
  position: relative;
}

.loading-spinner::after {
  content: '';
  position: absolute;
  top: 5px;
  left: 5px;
  right: 5px;
  bottom: 5px;
  border: 3px solid transparent;
  border-bottom-color: var(--primary);
  border-left-color: var(--accent);
  border-radius: 50%;
  animation: loadingSpin 1.5s linear infinite reverse;
}

@keyframes loadingSpin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-progress {
  color: var(--text-secondary);
  font-size: 1rem;
  letter-spacing: 1px;
}

/* 媒体查询调整 */
@media (max-width: 768px) {
  .game-instructions {
    padding: 10px;
  }
  
  .instructions-title {
    font-size: 1.1rem;
  }
  
  .instruction-section {
    min-width: 100%;
  }
  
  .mobile-hide {
    display: none;
  }
} 
    </style>
</head>
<body>
    <div class="game-container">
        <div class="game-header">
            <div class="title-container">
                <h1 class="game-title">科技蛇<span>TECH SNAKE</span></h1>
                <div class="reactor">
                    <div class="reactor-core"></div>
                    <div class="reactor-ring ring1"></div>
                    <div class="reactor-ring ring2"></div>
                    <div class="reactor-ring ring3"></div>
                </div>
            </div>
            
            <div class="game-stats">
                <div class="stat-box score">
                    <span class="stat-label">分数</span>
                    <span id="score" class="stat-value">0</span>
                </div>
                <div class="stat-box high-score">
                    <span class="stat-label">最高分</span>
                    <span id="highScore" class="stat-value">0</span>
                </div>
                <div class="stat-box length">
                    <span class="stat-label">长度</span>
                    <span id="length" class="stat-value">1</span>
                </div>
                <div class="stat-box time">
                    <span class="stat-label">时间</span>
                    <span id="time" class="stat-value">0:00</span>
                </div>
                <div class="stat-box ai-score">
                    <span class="stat-label">AI分数</span>
                    <span id="aiScore" class="stat-value">0</span>
                </div>
                <div class="stat-box ai-length">
                    <span class="stat-label">AI长度</span>
                    <span id="aiLength" class="stat-value">1</span>
                </div>
            </div>

            <div id="effects" class="effects-container">
                <div class="effects-title">活动效果</div>
                <div class="effects-items"></div>
            </div>
        </div>

        <div class="game-field">
            <!-- 游戏画布 -->
            <div class="canvas-container">
                <canvas id="gameCanvas" width="800" height="600"></canvas>
                <div class="grid-overlay"></div>
                <div class="scanline"></div>
            </div>
            
            <!-- 移动设备控制器 -->
            <div class="mobile-controls">
                <div class="controls-wrapper">
                    <div class="d-pad">
                        <button id="upBtn" class="direction-btn up-btn">
                            <svg viewBox="0 0 24 24"><path d="M12 8l-6 6 1.41 1.41L12 10.83l4.59 4.58L18 14z"/></svg>
                        </button>
                        <button id="leftBtn" class="direction-btn left-btn">
                            <svg viewBox="0 0 24 24"><path d="M15.41 16.59L10.83 12l4.58-4.59L14 6l-6 6 6 6z"/></svg>
                        </button>
                        <button id="rightBtn" class="direction-btn right-btn">
                            <svg viewBox="0 0 24 24"><path d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6z"/></svg>
                        </button>
                        <button id="downBtn" class="direction-btn down-btn">
                            <svg viewBox="0 0 24 24"><path d="M16.59 8.59L12 13.17 7.41 8.59 6 10l6 6 6-6z"/></svg>
                        </button>
                    </div>
                    <div class="action-buttons">
                        <button id="boostBtn" class="boost-btn">
                            <span class="boost-icon">加速</span>
                        </button>
                    </div>
                </div>
            </div>
            
            <div class="game-controls">
                <div class="control-panel">
                    <div class="control-group">
                        <label for="speedControl">速度控制</label>
                        <div class="slider-container">
                            <input type="range" id="speedControl" min="1" max="10" value="5">
                            <div class="slider-value" id="speedValue">5</div>
                        </div>
                    </div>
                    
                    <div class="control-group">
                        <label for="difficultySelect">难度选择</label>
                        <select id="difficultySelect" class="difficulty-select">
                            <option value="easy">低风险</option>
                            <option value="medium" selected>标准</option>
                            <option value="hard">高危险</option>
                        </select>
                    </div>
                </div>
                
                <div class="button-group">
                    <button id="startBtn" class="cyber-button">
                        <span class="button-content">启动</span>
                        <span class="button-glitch"></span>
                    </button>
                    <button id="pauseBtn" class="cyber-button">
                        <span class="button-content">暂停</span>
                        <span class="button-glitch"></span>
                    </button>
                    <button id="restartBtn" class="cyber-button">
                        <span class="button-content">重启</span>
                        <span class="button-glitch"></span>
                    </button>
                    <button id="obstacleModeBtn" class="cyber-button toggle-button">
                        <span class="button-content">障碍模式</span>
                        <span class="button-glitch"></span>
                    </button>
                    <button id="aiModeBtn" class="cyber-button toggle-button">
                        <span class="button-content">AI对战</span>
                        <span class="button-glitch"></span>
                    </button>
                </div>
            </div>
        </div>

        <div class="food-guide">
            <h3 class="guide-title">能量源</h3>
            <div class="food-items">
                <div class="food-item">
                    <div class="food-icon normal"></div>
                    <div class="food-info">
                        <span class="food-name">标准能量</span>
                        <span class="food-desc">+10分</span>
                    </div>
                </div>
                <div class="food-item">
                    <div class="food-icon speedBoost"></div>
                    <div class="food-info">
                        <span class="food-name">速度强化</span>
                        <span class="food-desc">+15分, 速度提升</span>
                    </div>
                </div>
                <div class="food-item">
                    <div class="food-icon doubleScore"></div>
                    <div class="food-info">
                        <span class="food-name">双倍增益</span>
                        <span class="food-desc">+20分, 得分翻倍</span>
                    </div>
                </div>
                <div class="food-item">
                    <div class="food-icon shield"></div>
                    <div class="food-info">
                        <span class="food-name">防护屏障</span>
                        <span class="food-desc">+25分, 免疫碰撞</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- 游戏介绍区域 -->
        <div class="game-instructions">
            <h3 class="instructions-title">游戏指南</h3>
            <div class="instructions-content">
                <div class="instruction-section">
                    <h4>基本操作</h4>
                    <ul>
                        <li><span class="key-highlight">方向键</span> 或 <span class="key-highlight">WASD</span> - 控制蛇的移动</li>
                        <li><span class="key-highlight">空格键</span> - 暂停/继续游戏</li>
                        <li>点击 <span class="key-highlight">加速</span> 按钮 - 临时提升速度</li>
                    </ul>
                </div>
                <div class="instruction-section">
                    <h4>游戏模式</h4>
                    <ul>
                        <li><span class="mode-highlight">标准模式</span> - 经典贪吃蛇玩法</li>
                        <li><span class="mode-highlight">障碍模式</span> - 地图中出现障碍物，增加挑战性</li>
                        <li><span class="mode-highlight">AI对战</span> - 与AI蛇竞争食物和分数</li>
                    </ul>
                </div>
                <div class="instruction-section mobile-hide">
                    <h4>提示技巧</h4>
                    <ul>
                        <li>吃到特殊食物可获得暂时的能力增益</li>
                        <li>护盾效果可以使蛇穿越边界，不会死亡</li>
                        <li>速度和难度会随着分数提升</li>
                        <li>速度越快，得分越高</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <!-- 游戏结束模态框 -->
    <div class="modal" id="gameOverModal">
        <div class="modal-content">
            <div class="particles" id="modalParticles"></div>
            <div class="modal-header">
                <span class="mode-badge" id="modeBadge">标准模式</span>
                <h2 class="modal-title">任务结束</h2>
            </div>
            <div class="score-container">
                <div class="score-item player-stats">
                    <span class="score-label">分数</span>
                    <span class="score-value" id="finalScore">0</span>
                </div>
                <div class="score-item player-stats">
                    <span class="score-label">长度</span>
                    <span class="score-value" id="finalLength">0</span>
                </div>
                <div class="score-item ai-stats" id="aiStatsContainer">
                    <span class="score-label">AI分数</span>
                    <span class="score-value" id="finalAiScore">0</span>
                </div>
                <div class="score-item ai-stats" id="aiLengthContainer">
                    <span class="score-label">AI长度</span>
                    <span class="score-value" id="finalAiLength">0</span>
                </div>
                <div class="score-item high-score">
                    <span class="score-label">最高分数</span>
                    <span class="score-value" id="finalHighScore">0</span>
                </div>
                <div class="score-item game-time">
                    <span class="score-label">游戏时间</span>
                    <span class="score-value" id="finalTime">0秒</span>
                </div>
            </div>
            <div class="modal-buttons">
                <button class="cyber-button" id="modalRestartBtn">
                    <span class="button-content">重新开始</span>
                    <span class="button-glitch"></span>
                </button>
                <button class="cyber-button" id="modalMenuBtn">
                    <span class="button-content">返回菜单</span>
                    <span class="button-glitch"></span>
                </button>
                <button class="cyber-button" id="modalShareBtn">
                    <span class="button-content">分享成绩</span>
                    <span class="button-glitch"></span>
                </button>
            </div>
        </div>
    </div>
    
    <!-- 初始化加载提示 -->
    <div class="loading-screen" id="loadingScreen">
        <div class="loading-content">
            <div class="loading-title">加载中</div>
            <div class="loading-spinner"></div>
            <div class="loading-progress">准备游戏资源...</div>
        </div>
    </div>

    <script>
      // 游戏状态管理
const game = {
  snake: [{x: 15, y: 15}],  // 蛇的初始位置
  aiSnake: [{x: 25, y: 15}], // AI蛇的初始位置
  food: {x: 5, y: 5, type: 'normal'},  // 食物的初始位置和类型
  direction: 'right',       // 初始方向
  aiDirection: 'left', // AI蛇的方向
  gridSize: 20,            // 网格大小
  speed: 200,              // 初始速度（毫秒）
  score: 0,                // 当前分数
  aiScore: 0, // AI的分数
  highScore: 0,            // 最高分
  isRunning: false,        // 游戏运行状态
  isPaused: false,         // 游戏暂停状态
  startTime: 0,            // 游戏开始时间
  gameTime: 0,             // 游戏运行时间
  obstacleMode: false,     // 障碍模式状态
  obstacles: [],           // 障碍物数组
  difficulty: 'medium',    // 游戏难度
  aiMode: false, // AI对战模式
  stars: [],               // 背景星星
  animationFrameId: null,  // 请求动画帧ID
  effects: {               // 特殊效果状态
    speedBoost: false,     // 速度提升
    speedBoostEndTime: 0,  // 速度提升结束时间
    doubleScore: false,    // 双倍分数
    doubleScoreEndTime: 0, // 双倍分数结束时间
    shield: false,         // 护盾
    shieldEndTime: 0       // 护盾结束时间
  }
};

// 难度设置
const DIFFICULTY_SETTINGS = {
  easy: {
    obstacleCount: {min: 3, max: 5},
    foodProbability: {normal: 0.8, speedBoost: 0.07, doubleScore: 0.07, shield: 0.06},
    scoreMultiplier: 1
  },
  medium: {
    obstacleCount: {min: 5, max: 8},
    foodProbability: {normal: 0.7, speedBoost: 0.1, doubleScore: 0.1, shield: 0.1},
    scoreMultiplier: 1.5
  },
  hard: {
    obstacleCount: {min: 8, max: 12},
    foodProbability: {normal: 0.6, speedBoost: 0.15, doubleScore: 0.15, shield: 0.1},
    scoreMultiplier: 2
  }
};

// 食物类型定义
const FOOD_TYPES = {
  normal: {
    color: '#4CAF50',
    score: 10,
    probability: 0.7,
    effect: null
  },
  speedBoost: {
    color: '#FFC107',
    score: 15,
    probability: 0.1,
    effect: 'speedBoost',
    duration: 5000 // 5秒
  },
  doubleScore: {
    color: '#9C27B0',
    score: 20,
    probability: 0.1,
    effect: 'doubleScore',
    duration: 8000 // 8秒
  },
  shield: {
    color: '#2196F3',
    score: 25,
    probability: 0.1,
    effect: 'shield',
    duration: 10000 // 10秒
  }
};

// 获取画布上下文
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

// 粒子系统
let particles = [];

// 页面加载完成时初始化游戏
window.addEventListener('load', function() {
  // 设置画布大小
  resizeCanvas();
  
  // 窗口大小改变时重设画布
  window.addEventListener('resize', resizeCanvas);
  
  // 从本地存储获取最高分
  const storedHighScore = localStorage.getItem('snakeHighScore');
  if (storedHighScore) {
    game.highScore = parseInt(storedHighScore);
    document.getElementById('highScore').textContent = game.highScore;
  }
  
  // 初始化游戏
  initGame();
  
  // 绑定游戏控制按钮事件
  document.getElementById('startBtn').addEventListener('click', startGame);
  document.getElementById('pauseBtn').addEventListener('click', togglePause);
  document.getElementById('restartBtn').addEventListener('click', restartGame);
  document.getElementById('obstacleModeBtn').addEventListener('click', toggleObstacleMode);
  document.getElementById('aiModeBtn').addEventListener('click', toggleAIMode);
  
  // 速度控制
  const speedControl = document.getElementById('speedControl');
  speedControl.addEventListener('input', function() {
    const speed = parseInt(speedControl.value);
    game.speed = 300 - (speed * 25); // 将1-10的值转换为275-50毫秒
    document.getElementById('speedValue').textContent = speed;
  });
  
  // 难度选择
  document.getElementById('difficultySelect').addEventListener('change', function() {
    game.difficulty = this.value;
    
    // 更新按钮样式反馈
    const buttons = document.querySelectorAll('.cyber-button');
    buttons.forEach(btn => {
      btn.classList.add('active');
      setTimeout(() => {
        btn.classList.remove('active');
      }, 300);
    });
    
    if (game.obstacleMode) {
      // 如果当前是障碍模式，重新生成障碍物以应用新难度
      generateObstacles();
    }
  });
  
  // 移动控制
  initMobileControls();
  
  // 初始化动画效果
  initVisualEffects();
  
  // 绘制初始状态
  draw();
});

// 调整画布大小以适应屏幕
function resizeCanvas() {
  const container = document.querySelector('.canvas-container');
  const containerWidth = container.clientWidth;
  
  // 设置画布宽度与容器相同
  canvas.width = containerWidth;
  
  // 根据屏幕大小调整网格大小
  if (window.innerWidth < 760) {
    game.gridSize = 15; // 小屏幕使用更小的网格
  } else {
    game.gridSize = 20; // 普通屏幕使用标准网格
  }
  
  // 让画布保持接近正方形
  canvas.height = Math.min(containerWidth, window.innerHeight * 0.6);
  
  // 重新绘制
  if (game.isRunning) {
    draw();
  }
  
  // 更新网格覆盖层
  document.querySelector('.grid-overlay').style.backgroundSize = `${game.gridSize}px ${game.gridSize}px`;
}

// 初始化游戏
function initGame() {
  // 如果有活动的动画帧请求，取消它
  if (game.animationFrameId) {
    cancelAnimationFrame(game.animationFrameId);
    game.animationFrameId = null;
  }
  
  // 计算中心位置
  const centerX = Math.floor(canvas.width / (2 * game.gridSize));
  const centerY = Math.floor(canvas.height / (2 * game.gridSize));

  // 重置游戏状态
  game.snake = [
    {x: centerX, y: centerY},
    {x: centerX - 1, y: centerY},
    {x: centerX - 2, y: centerY}
  ];
  game.aiSnake = [
    {x: centerX + 5, y: centerY},
    {x: centerX + 4, y: centerY},
    {x: centerX + 3, y: centerY}
  ];
  game.direction = 'right';
  game.aiDirection = 'left';
  game.score = 0;
  game.aiScore = 0;
  game.isRunning = false;
  game.isPaused = false;
  game.startTime = 0;
  game.gameTime = 0;
  game.obstacles = [];
  
  // 清空所有粒子
  particles = [];
  
  // 重新生成背景星星
  game.stars = [];
  
  // 重置特殊效果
  game.effects = {
    speedBoost: false,
    speedBoostEndTime: 0,
    doubleScore: false,
    doubleScoreEndTime: 0,
    shield: false,
    shieldEndTime: 0
  };
  
  // 生成第一个食物
  generateFood();
  
  // 如果障碍模式开启，生成障碍物
  if (game.obstacleMode) {
    generateObstacles();
  }
  
  // 隐藏AI相关显示
  hideAIStats();
  
  // 清空特效显示
  clearEffectsDisplay();
  
  // 更新显示
  updateDisplay();
  
  // 重置按钮状态
  document.getElementById('startBtn').style.display = 'block';
  document.getElementById('pauseBtn').style.display = 'none';
  document.getElementById('pauseBtn').querySelector('.button-content').textContent = '暂停';
  
  // 移除暂停样式
  document.querySelector('.canvas-container').classList.remove('paused');
  
  // 绘制初始状态
  draw();
}

// 隐藏AI相关显示
function hideAIStats() {
  document.querySelectorAll('.ai-score, .ai-length').forEach(el => {
    el.style.display = 'none';
  });
}

// 显示AI相关显示
function showAIStats() {
  document.querySelectorAll('.ai-score, .ai-length').forEach(el => {
    el.style.display = 'flex';
  });
}

// 初始化移动控制
function initMobileControls() {
  // 方向按钮控制
  document.getElementById('upBtn').addEventListener('touchstart', function(e) {
    e.preventDefault();
    if (game.direction !== 'down') {
      game.direction = 'up';
    }
  });
  
  document.getElementById('downBtn').addEventListener('touchstart', function(e) {
    e.preventDefault();
    if (game.direction !== 'up') {
      game.direction = 'down';
    }
  });
  
  document.getElementById('leftBtn').addEventListener('touchstart', function(e) {
    e.preventDefault();
    if (game.direction !== 'right') {
      game.direction = 'left';
    }
  });
  
  document.getElementById('rightBtn').addEventListener('touchstart', function(e) {
    e.preventDefault();
    if (game.direction !== 'left') {
      game.direction = 'right';
    }
  });
  
  // 为了更好的响应体验，同时绑定点击事件
  document.getElementById('upBtn').addEventListener('click', function() {
    if (game.direction !== 'down') {
      game.direction = 'up';
    }
  });
  
  document.getElementById('downBtn').addEventListener('click', function() {
    if (game.direction !== 'up') {
      game.direction = 'down';
    }
  });
  
  document.getElementById('leftBtn').addEventListener('click', function() {
    if (game.direction !== 'right') {
      game.direction = 'left';
    }
  });
  
  document.getElementById('rightBtn').addEventListener('click', function() {
    if (game.direction !== 'left') {
      game.direction = 'right';
    }
  });
  
  // 加速按钮控制
  const boostBtn = document.getElementById('boostBtn');
  
  // 按下加速按钮时的处理
  const activateBoost = function() {
    // 只有在游戏运行且未暂停时才能使用加速
    if (game.isRunning && !game.isPaused) {
      // 临时加速效果（持续2秒）
      game.effects.speedBoost = true;
      game.effects.speedBoostEndTime = Date.now() + 2000; // 2秒
      
      // 添加加速视觉反馈
      boostBtn.classList.add('active');
      
      // 添加特效显示
      updateEffectsDisplay();
      
      // 播放加速音效
      playSound('speedBoost');
      
      // 2秒后移除按钮活跃状态
      setTimeout(() => {
        boostBtn.classList.remove('active');
      }, 2000);
    }
  };
  
  // 绑定触摸和点击事件
  boostBtn.addEventListener('touchstart', function(e) {
    e.preventDefault();
    activateBoost();
  });
  
  boostBtn.addEventListener('click', activateBoost);
  
  // 防止向下滚动
  document.querySelectorAll('.direction-btn, .boost-btn').forEach(btn => {
    btn.addEventListener('touchmove', function(e) {
      e.preventDefault();
    });
  });
}

// 初始化视觉效果
function initVisualEffects() {
  // 添加按钮悬停音效
  document.querySelectorAll('.cyber-button').forEach(btn => {
    btn.addEventListener('mouseenter', () => {
      playSound('hover');
    });
    btn.addEventListener('click', () => {
      playSound('click');
    });
  });
}

// 播放音效（简单版本，可扩展）
function playSound(type) {
  // 使用现代音频API创建简单的合成音效
  try {
    const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    const oscillator = audioCtx.createOscillator();
    const gainNode = audioCtx.createGain();
    
    oscillator.connect(gainNode);
    gainNode.connect(audioCtx.destination);
    
    if (type === 'hover') {
      oscillator.type = 'sine';
      oscillator.frequency.value = 600;
      gainNode.gain.value = 0.05;
      oscillator.start();
      oscillator.stop(audioCtx.currentTime + 0.1);
    } else if (type === 'click') {
      oscillator.type = 'square';
      oscillator.frequency.value = 800;
      gainNode.gain.value = 0.1;
      oscillator.start();
      oscillator.stop(audioCtx.currentTime + 0.15);
    } else if (type === 'food') {
      oscillator.type = 'sine';
      oscillator.frequency.value = 1200;
      gainNode.gain.value = 0.1;
      oscillator.start();
      
      // 频率缓降
      oscillator.frequency.exponentialRampToValueAtTime(300, audioCtx.currentTime + 0.3);
      gainNode.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + 0.3);
      oscillator.stop(audioCtx.currentTime + 0.3);
    } else if (type === 'gameOver') {
      oscillator.type = 'sawtooth';
      oscillator.frequency.value = 200;
      gainNode.gain.value = 0.15;
      oscillator.start();
      
      // 频率缓降
      oscillator.frequency.exponentialRampToValueAtTime(50, audioCtx.currentTime + 1);
      gainNode.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + 1);
      oscillator.stop(audioCtx.currentTime + 1);
    } else if (type === 'speedBoost') {
      // 加速音效 - 快速上升的音调
      oscillator.type = 'triangle';
      oscillator.frequency.value = 300;
      gainNode.gain.value = 0.15;
      oscillator.start();
      
      // 频率快速上升
      oscillator.frequency.exponentialRampToValueAtTime(1200, audioCtx.currentTime + 0.2);
      gainNode.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + 0.5);
      oscillator.stop(audioCtx.currentTime + 0.5);
    }
  } catch (e) {
    console.log('音频API不支持或被阻止:', e);
  }
}

// 开始游戏
function startGame() {
  if (!game.isRunning) {
    // 重置动画帧ID
    if (game.animationFrameId) {
      cancelAnimationFrame(game.animationFrameId);
      game.animationFrameId = null;
    }
    
    game.isRunning = true;
    game.isPaused = false;
    game.startTime = Date.now();
    document.getElementById('startBtn').style.display = 'none';
    document.getElementById('pauseBtn').style.display = 'block';
    
    // 添加开始游戏动画效果
    addGlitchEffect();
    playSound('click');
    
    // 启动游戏循环
    gameLoop();
  }
}

// 添加故障效果
function addGlitchEffect() {
  const canvas = document.querySelector('.canvas-container');
  canvas.classList.add('glitch');
  setTimeout(() => {
    canvas.classList.remove('glitch');
  }, 500);
}

// 暂停/继续游戏
function togglePause() {
  if (!game.isRunning) return;
  
  game.isPaused = !game.isPaused;
  const pauseBtn = document.getElementById('pauseBtn');
  
  if (game.isPaused) {
    pauseBtn.querySelector('.button-content').textContent = '继续';
    // 添加暂停时的视觉效果
    document.querySelector('.canvas-container').classList.add('paused');
  } else {
    pauseBtn.querySelector('.button-content').textContent = '暂停';
    document.querySelector('.canvas-container').classList.remove('paused');
    
    // 使用animationFrameId来控制游戏循环
    if (!game.animationFrameId) {
      gameLoop(); // 只有在没有活动的游戏循环时才启动新的循环
    }
  }
  
  playSound('click');
}

// 重新开始游戏
function restartGame() {
  // 停止当前游戏
  if (game.isRunning) {
    game.isRunning = false;
  }
  
  // 完全初始化游戏
  initGame();
  
  // 确保所有UI元素都恢复到初始状态
  document.querySelectorAll('.cyber-button.active').forEach(btn => {
    btn.classList.remove('active');
  });
  
  // 如果有障碍模式或AI模式被启用，恢复其按钮的状态
  if (game.obstacleMode) {
    document.getElementById('obstacleModeBtn').classList.add('active');
  }
  if (game.aiMode) {
    document.getElementById('aiModeBtn').classList.add('active');
    showAIStats();
  }
  
  playSound('click');
}

// 切换障碍物模式
function toggleObstacleMode() {
  game.obstacleMode = !game.obstacleMode;
  
  const obstacleBtn = document.getElementById('obstacleModeBtn');
  
  if (game.obstacleMode) {
    obstacleBtn.classList.add('active');
    generateObstacles();
  } else {
    obstacleBtn.classList.remove('active');
    game.obstacles = [];
    // 清除粒子效果
    particles = [];
  }
  
  // 重新绘制游戏
  draw();
  playSound('click');
}

// 切换AI模式
function toggleAIMode() {
  game.aiMode = !game.aiMode;
  
  const aiBtn = document.getElementById('aiModeBtn');
  
  if (game.aiMode) {
    aiBtn.classList.add('active');
    showAIStats();
    
    // 移除自动启动游戏的代码
    // if (!game.isRunning) {
    //   startGame();
    // }
  } else {
    aiBtn.classList.remove('active');
    hideAIStats();
    // 确保清除所有与AI相关的粒子效果
    particles = particles.filter(p => p.color !== '#9C27B0'); // 假设AI相关粒子颜色
  }
  
  // 重新绘制游戏
  draw();
  playSound('click');
}

// 生成障碍物
function generateObstacles() {
  if (!game.obstacleMode) return;
  
  // 清空现有障碍物
  game.obstacles = [];
  
  // 根据难度设置障碍物数量
  const diffSettings = DIFFICULTY_SETTINGS[game.difficulty];
  const obstacleCount = Math.floor(Math.random() * 
    (diffSettings.obstacleCount.max - diffSettings.obstacleCount.min + 1)) + 
    diffSettings.obstacleCount.min;
  
  // 计算网格数量
  const gridWidth = Math.floor(canvas.width / game.gridSize);
  const gridHeight = Math.floor(canvas.height / game.gridSize);
  
  // 生成障碍物
  for (let i = 0; i < obstacleCount; i++) {
    let obstacle;
    let isValid = false;
    
    // 尝试生成不与蛇、食物和其他障碍物重叠的障碍物位置
    while (!isValid) {
      obstacle = {
        x: Math.floor(Math.random() * gridWidth),
        y: Math.floor(Math.random() * gridHeight)
      };
      
      isValid = true;
      
      // 检查是否与蛇重叠
      for (const segment of game.snake) {
        if (segment.x === obstacle.x && segment.y === obstacle.y) {
          isValid = false;
          break;
        }
      }
      
      // 检查是否与AI蛇重叠
      if (isValid && game.aiMode) {
        for (const segment of game.aiSnake) {
          if (segment.x === obstacle.x && segment.y === obstacle.y) {
            isValid = false;
            break;
          }
        }
      }
      
      // 检查是否与食物重叠
      if (isValid && game.food && 
          obstacle.x === game.food.x && obstacle.y === game.food.y) {
        isValid = false;
      }
      
      // 检查是否与其他障碍物重叠
      if (isValid) {
        for (const existing of game.obstacles) {
          if (existing.x === obstacle.x && existing.y === obstacle.y) {
            isValid = false;
            break;
          }
        }
      }
    }
    
    game.obstacles.push(obstacle);
  }
  
  // 创建障碍物出现的视觉效果
  createObstacleEffect();
}

// 创建障碍物出现的视觉效果
function createObstacleEffect() {
  // 为每个障碍物创建一个动画效果
  game.obstacles.forEach(obstacle => {
    createParticles(
      obstacle.x * game.gridSize + game.gridSize/2, 
      obstacle.y * game.gridSize + game.gridSize/2,
      10,
      '#795548'
    );
  });
}

// 生成食物
function generateFood() {
  // 计算网格数量
  const gridWidth = Math.floor(canvas.width / game.gridSize);
  const gridHeight = Math.floor(canvas.height / game.gridSize);
  
  let foodX, foodY, isValid;
  
  // 尝试生成不与蛇、AI蛇和障碍物重叠的食物位置
  do {
    foodX = Math.floor(Math.random() * gridWidth);
    foodY = Math.floor(Math.random() * gridHeight);
    isValid = true;
    
    // 检查是否与蛇重叠
    for (const segment of game.snake) {
      if (segment.x === foodX && segment.y === foodY) {
        isValid = false;
        break;
      }
    }
    
    // 检查是否与AI蛇重叠
    if (isValid && game.aiMode) {
      for (const segment of game.aiSnake) {
        if (segment.x === foodX && segment.y === foodY) {
          isValid = false;
          break;
        }
      }
    }
    
    // 检查是否与障碍物重叠
    if (isValid && game.obstacleMode) {
      for (const obstacle of game.obstacles) {
        if (obstacle.x === foodX && obstacle.y === foodY) {
          isValid = false;
          break;
        }
      }
    }
  } while (!isValid);
  
  // 选择食物类型
  const foodType = selectFoodType();
  
  // 创建新食物
  game.food = {
    x: foodX,
    y: foodY,
    type: foodType
  };
  
  // 食物出现的视觉效果
  createFoodEffect();
}

// 创建食物出现的视觉效果
function createFoodEffect() {
  const x = game.food.x * game.gridSize + game.gridSize/2;
  const y = game.food.y * game.gridSize + game.gridSize/2;
  const color = FOOD_TYPES[game.food.type].color;
  
  // 创建粒子效果
  createParticles(x, y, 15, color);
}

// 选择食物类型
function selectFoodType() {
  const diffSettings = DIFFICULTY_SETTINGS[game.difficulty];
  const foodProb = diffSettings.foodProbability;
  
  const random = Math.random();
  let cumProb = 0;
  
  for (const [type, prob] of Object.entries(foodProb)) {
    cumProb += prob;
    if (random <= cumProb) {
      return type;
    }
  }
  
  return 'normal'; // 默认返回普通食物
}

// 创建粒子效果
function createParticles(x, y, count, color) {
  for (let i = 0; i < count; i++) {
    particles.push({
      x: x,
      y: y,
      vx: (Math.random() - 0.5) * 3,
      vy: (Math.random() - 0.5) * 3,
      radius: Math.random() * 3 + 1,
      color: color,
      alpha: 1,
      life: 30
    });
  }
}

// 更新粒子
function updateParticles() {
  particles = particles.filter(p => p.alpha > 0);
  
  particles.forEach(p => {
    p.x += p.vx;
    p.y += p.vy;
    p.life--;
    p.alpha = p.life / 30;
  });
}

// 绘制粒子
function drawParticles() {
  particles.forEach(p => {
    ctx.globalAlpha = p.alpha;
    ctx.fillStyle = p.color;
    ctx.beginPath();
    ctx.arc(p.x, p.y, p.radius, 0, Math.PI * 2);
    ctx.fill();
  });
  ctx.globalAlpha = 1;
}

// 添加特效显示
function addEffectElement(name, duration, color) {
  const effectsContainer = document.querySelector('.effects-items');
  if (!effectsContainer) return;
  
  const effectEl = document.createElement('div');
  effectEl.className = 'effect';
  effectEl.innerHTML = `<span style="font-weight:500">${name}</span>: <span style="color:white;text-shadow:0 0 5px ${color}">${duration}s</span>`;
  effectEl.style.color = color;
  effectEl.style.borderLeftColor = color;
  effectEl.style.animation = `fadeIn 0.3s, glow 1.5s infinite alternate`;
  
  effectsContainer.appendChild(effectEl);
}

// 清空特效显示
function clearEffectsDisplay() {
  const effectsContainer = document.querySelector('.effects-items');
  if (effectsContainer) {
    effectsContainer.innerHTML = '';
  }
}

// 更新显示
function updateDisplay() {
  // 更新分数
  document.getElementById('score').textContent = game.score;
  document.getElementById('highScore').textContent = game.highScore;
  
  // 更新长度
  document.getElementById('length').textContent = game.snake.length;
  
  // 更新时间
  const minutes = Math.floor(game.gameTime / 60);
  const seconds = Math.floor(game.gameTime % 60);
  document.getElementById('time').textContent = 
    `${minutes}:${seconds.toString().padStart(2, '0')}`;
  
  // 更新AI分数显示
  if (game.aiMode) {
    document.getElementById('aiScore').textContent = game.aiScore;
    document.getElementById('aiLength').textContent = game.aiSnake.length;
  }
}

// 更新特殊效果显示
function updateEffectsDisplay() {
  clearEffectsDisplay();
  
  const now = Date.now();
  
  if (game.effects.speedBoost && now < game.effects.speedBoostEndTime) {
    const timeLeft = Math.ceil((game.effects.speedBoostEndTime - now) / 1000);
    addEffectElement('速度强化', timeLeft, '#FFC107');
  } else {
    game.effects.speedBoost = false;
  }
  
  if (game.effects.doubleScore && now < game.effects.doubleScoreEndTime) {
    const timeLeft = Math.ceil((game.effects.doubleScoreEndTime - now) / 1000);
    addEffectElement('双倍得分', timeLeft, '#9C27B0');
  } else {
    game.effects.doubleScore = false;
  }
  
  if (game.effects.shield && now < game.effects.shieldEndTime) {
    const timeLeft = Math.ceil((game.effects.shieldEndTime - now) / 1000);
    addEffectElement('防护屏障', timeLeft, '#2196F3');
  } else {
    game.effects.shield = false;
  }
}

// 检查特殊效果
function checkEffects() {
  const now = Date.now();
  
  // 检查效果是否过期
  if (game.effects.speedBoost && now >= game.effects.speedBoostEndTime) {
    game.effects.speedBoost = false;
  }
  
  if (game.effects.doubleScore && now >= game.effects.doubleScoreEndTime) {
    game.effects.doubleScore = false;
  }
  
  if (game.effects.shield && now >= game.effects.shieldEndTime) {
    game.effects.shield = false;
  }
  
  // 更新效果显示
  updateEffectsDisplay();
}

// 游戏循环
function gameLoop() {
  if (!game.isRunning) return;
  if (game.isPaused) {
    game.animationFrameId = requestAnimationFrame(gameLoop);
    return;
  }
  
  // 更新游戏时间
  const currentTime = Date.now();
  game.gameTime = (currentTime - game.startTime) / 1000;
  
  // 检查特殊效果状态
  checkEffects();
  
  // 更新粒子效果
  updateParticles();
  
  // 移动蛇
  moveSnake();
  
  // 如果游戏结束，不执行后续代码
  if (!game.isRunning) return;
  
  // 移动AI蛇
  if (game.aiMode) {
    moveAISnake();
  }
  
  // 更新显示
  updateDisplay();
  
  // 绘制游戏画面
  draw();
  
  // 设置下一次更新的时间
  const speed = game.effects.speedBoost ? game.speed * 0.7 : game.speed;
  setTimeout(() => {
    game.animationFrameId = requestAnimationFrame(gameLoop);
  }, speed);
}

// 移动蛇
function moveSnake() {
  // 获取蛇头
  const head = {...game.snake[0]};
  
  // 根据方向移动
  switch (game.direction) {
    case 'up': head.y--; break;
    case 'down': head.y++; break;
    case 'left': head.x--; break;
    case 'right': head.x++; break;
  }
  
  // 检查碰撞
  if (checkCollision(head)) {
    gameOver();
    return;
  }
  
  // 将新头部添加到蛇身
  game.snake.unshift(head);
  
  // 检查是否吃到食物
  if (game.food && head.x === game.food.x && head.y === game.food.y) {
    // 播放音效
    playSound('food');
    
    // 应用食物效果
    applyFoodEffect(game.food.type);
    
    // 更新分数
    const baseScore = FOOD_TYPES[game.food.type].score;
    const diffMultiplier = DIFFICULTY_SETTINGS[game.difficulty].scoreMultiplier;
    const doubleMultiplier = game.effects.doubleScore ? 2 : 1;
    game.score += Math.floor(baseScore * diffMultiplier * doubleMultiplier);
    
    // 创建得分动画
    createScoreAnimation(head.x, head.y, Math.floor(baseScore * diffMultiplier * doubleMultiplier));
    
    // 更新最高分
    if (game.score > game.highScore) {
      game.highScore = game.score;
      localStorage.setItem('snakeHighScore', game.highScore);
    }
    
    // 生成新食物
    generateFood();
  } else {
    // 未吃到食物，移除尾部
    game.snake.pop();
  }
}

// 创建得分动画
function createScoreAnimation(x, y, score) {
  const scoreEl = document.createElement('div');
  scoreEl.className = 'score-pop';
  scoreEl.textContent = `+${score}`;
  
  // 计算位置（相对于画布）
  const canvasRect = canvas.getBoundingClientRect();
  const posX = x * game.gridSize + canvasRect.left;
  const posY = y * game.gridSize + canvasRect.top;
  
  scoreEl.style.left = `${posX}px`;
  scoreEl.style.top = `${posY}px`;
  
  document.body.appendChild(scoreEl);
  
  // 动画结束后移除元素
  setTimeout(() => {
    scoreEl.remove();
  }, 1000);
}

// 移动AI蛇
function moveAISnake() {
  if (!game.aiMode) return;
  
  // 获取AI蛇头和食物位置
  const head = {...game.aiSnake[0]};
  const food = game.food;
  
  // 简单的AI决策：尝试移动到食物位置
  let newDirection = game.aiDirection;
  
  // 水平方向优先
  if (head.x < food.x && game.aiDirection !== 'left') {
    newDirection = 'right';
  } else if (head.x > food.x && game.aiDirection !== 'right') {
    newDirection = 'left';
  } else if (head.y < food.y && game.aiDirection !== 'up') {
    newDirection = 'down';
  } else if (head.y > food.y && game.aiDirection !== 'down') {
    newDirection = 'up';
  }
  
  // 检查新方向是否导致碰撞，如果是则尝试其他方向
  const directions = ['up', 'right', 'down', 'left'];
  const opposites = {
    'up': 'down',
    'down': 'up',
    'left': 'right',
    'right': 'left'
  };
  
  let newHead = {...head};
  switch (newDirection) {
    case 'up': newHead.y--; break;
    case 'down': newHead.y++; break;
    case 'left': newHead.x--; break;
    case 'right': newHead.x++; break;
  }
  
  // 如果新方向会导致碰撞，尝试其他方向
  if (checkAICollision(newHead)) {
    for (const dir of directions) {
      // 跳过与当前方向相反的方向
      if (dir === opposites[game.aiDirection]) continue;
      
      // 创建新的头部位置
      newHead = {...head};
      switch (dir) {
        case 'up': newHead.y--; break;
        case 'down': newHead.y++; break;
        case 'left': newHead.x--; break;
        case 'right': newHead.x++; break;
      }
      
      // 检查该方向是否安全
      if (!checkAICollision(newHead)) {
        newDirection = dir;
        break;
      }
    }
  }
  
  // 更新AI蛇方向
  game.aiDirection = newDirection;
  
  // 根据新方向移动
  switch (newDirection) {
    case 'up': head.y--; break;
    case 'down': head.y++; break;
    case 'left': head.x--; break;
    case 'right': head.x++; break;
  }
  
  // 检查碰撞
  if (checkAICollision(head)) {
    // AI蛇碰撞，玩家获胜
    game.aiMode = false;
    hideAIStats();
    document.getElementById('aiModeBtn').classList.remove('active');
    return;
  }
  
  // 将新头部添加到AI蛇身
  game.aiSnake.unshift(head);
  
  // 检查是否吃到食物
  if (game.food && head.x === game.food.x && head.y === game.food.y) {
    // 更新AI分数
    game.aiScore += FOOD_TYPES[game.food.type].score;
    
    // 生成新食物
    generateFood();
  } else {
    // 未吃到食物，移除尾部
    game.aiSnake.pop();
  }
}

// 检查蛇的碰撞
function checkCollision(head) {
  // 如果有护盾，不检查碰撞
  if (game.effects.shield) return false;
  
  // 计算网格数量
  const gridWidth = Math.floor(canvas.width / game.gridSize);
  const gridHeight = Math.floor(canvas.height / game.gridSize);
  
  // 检查边界碰撞
  if (head.x < 0 || head.x >= gridWidth || head.y < 0 || head.y >= gridHeight) {
    return true;
  }
  
  // 检查自身碰撞
  for (let i = 1; i < game.snake.length; i++) {
    if (head.x === game.snake[i].x && head.y === game.snake[i].y) {
      return true;
    }
  }
  
  // 检查障碍物碰撞
  if (game.obstacleMode) {
    for (const obstacle of game.obstacles) {
      if (head.x === obstacle.x && head.y === obstacle.y) {
        return true;
      }
    }
  }
  
  // 检查与AI蛇的碰撞
  if (game.aiMode) {
    for (const segment of game.aiSnake) {
      if (head.x === segment.x && head.y === segment.y) {
        return true;
      }
    }
  }
  
  return false;
}

// 检查AI蛇的碰撞
function checkAICollision(head) {
  // 计算网格数量
  const gridWidth = Math.floor(canvas.width / game.gridSize);
  const gridHeight = Math.floor(canvas.height / game.gridSize);
  
  // 检查边界碰撞
  if (head.x < 0 || head.x >= gridWidth || head.y < 0 || head.y >= gridHeight) {
    return true;
  }
  
  // 检查自身碰撞
  for (let i = 1; i < game.aiSnake.length; i++) {
    if (head.x === game.aiSnake[i].x && head.y === game.aiSnake[i].y) {
      return true;
    }
  }
  
  // 检查障碍物碰撞
  if (game.obstacleMode) {
    for (const obstacle of game.obstacles) {
      if (head.x === obstacle.x && head.y === obstacle.y) {
        return true;
      }
    }
  }
  
  // 检查与玩家蛇的碰撞
  for (const segment of game.snake) {
    if (head.x === segment.x && head.y === segment.y) {
      return true;
    }
  }
  
  return false;
}

// 应用食物效果
function applyFoodEffect(foodType) {
  if (foodType === 'normal') return;
  
  const now = Date.now();
  const foodConfig = FOOD_TYPES[foodType];
  
  switch (foodType) {
    case 'speedBoost':
      game.effects.speedBoost = true;
      game.effects.speedBoostEndTime = now + foodConfig.duration;
      break;
      
    case 'doubleScore':
      game.effects.doubleScore = true;
      game.effects.doubleScoreEndTime = now + foodConfig.duration;
      break;
      
    case 'shield':
      game.effects.shield = true;
      game.effects.shieldEndTime = now + foodConfig.duration;
      break;
  }
  
  // 更新效果显示
  updateEffectsDisplay();
}

// 绘制游戏
function draw() {
  // 清除画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  // 绘制背景
  drawBackground();
  
  // 绘制障碍物（如果启用了障碍模式）
  if (game.obstacleMode) {
    drawObstacles();
  }
  
  // 绘制食物
  if (game.food) {
    drawFood();
  }
  
  // 绘制蛇
  drawSnake(game.snake, true);
  
  // 绘制AI蛇（如果启用了AI模式）
  if (game.aiMode) {
    drawSnake(game.aiSnake, false);
  }
  
  // 绘制粒子
  drawParticles();
}

// 绘制背景效果
function drawBackground() {
  // 绘制深色背景
  ctx.fillStyle = '#000814';
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  
  // 初始化星星（如果还没有）
  if (!game.stars || game.stars.length === 0) {
    game.stars = [];
    for (let i = 0; i < 50; i++) {
      game.stars.push({
        x: Math.random() * canvas.width,
        y: Math.random() * canvas.height,
        radius: Math.random() * 1.5,
        alpha: Math.random() * 0.5 + 0.1,
        hue: 180 + Math.random() * 40
      });
    }
  }
  
  // 绘制星星并添加脉动动画
  const pulseFactor = 0.5 + 0.5 * Math.sin(Date.now() / 1000);
  
  for (const star of game.stars) {
    ctx.fillStyle = `hsla(${star.hue}, 100%, 70%, ${star.alpha * pulseFactor})`;
    ctx.beginPath();
    ctx.arc(star.x, star.y, star.radius, 0, Math.PI * 2);
    ctx.fill();
  }
}

// 绘制障碍物
function drawObstacles() {
  const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
  gradient.addColorStop(0, '#795548');
  gradient.addColorStop(1, '#5D4037');
  
  ctx.fillStyle = gradient;
  ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
  ctx.shadowBlur = 10;
  
  for (const obstacle of game.obstacles) {
    // 绘制圆角矩形
    const x = obstacle.x * game.gridSize;
    const y = obstacle.y * game.gridSize;
    const size = game.gridSize - 2;
    const radius = size / 4;
    
    ctx.beginPath();
    ctx.moveTo(x + radius, y);
    ctx.lineTo(x + size - radius, y);
    ctx.quadraticCurveTo(x + size, y, x + size, y + radius);
    ctx.lineTo(x + size, y + size - radius);
    ctx.quadraticCurveTo(x + size, y + size, x + size - radius, y + size);
    ctx.lineTo(x + radius, y + size);
    ctx.quadraticCurveTo(x, y + size, x, y + size - radius);
    ctx.lineTo(x, y + radius);
    ctx.quadraticCurveTo(x, y, x + radius, y);
    ctx.closePath();
    ctx.fill();
    
    // 添加科技纹理
    ctx.strokeStyle = 'rgba(0, 0, 0, 0.3)';
    ctx.lineWidth = 1;
    ctx.beginPath();
    ctx.moveTo(x + 2, y + size/2);
    ctx.lineTo(x + size - 2, y + size/2);
    ctx.stroke();
    
    ctx.beginPath();
    ctx.moveTo(x + size/2, y + 2);
    ctx.lineTo(x + size/2, y + size - 2);
    ctx.stroke();
  }
  
  ctx.shadowBlur = 0;
}

// 绘制食物
function drawFood() {
  const foodType = game.food.type;
  const foodColor = FOOD_TYPES[foodType].color;
  
  // 食物位置
  const x = game.food.x * game.gridSize + game.gridSize / 2;
  const y = game.food.y * game.gridSize + game.gridSize / 2;
  const radius = game.gridSize / 2 - 2;
  
  // 添加辉光效果
  ctx.shadowColor = foodColor;
  ctx.shadowBlur = 15;
  
  // 绘制食物底色（脉动效果）
  const pulseFactor = 0.1 * Math.sin(Date.now() / 200) + 0.9;
  const pulseRadius = radius * pulseFactor;
  
  // 渐变填充
  const gradient = ctx.createRadialGradient(
    x - radius/3, y - radius/3, 0,
    x, y, pulseRadius
  );
  gradient.addColorStop(0, '#fff');
  gradient.addColorStop(0.6, foodColor);
  gradient.addColorStop(1, 'rgba(0,0,0,0.5)');
  
  ctx.fillStyle = gradient;
  ctx.beginPath();
  ctx.arc(x, y, pulseRadius, 0, Math.PI * 2);
  ctx.fill();
  
  // 根据食物类型添加图标
  ctx.fillStyle = '#fff';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.shadowBlur = 0;
  
  switch (foodType) {
    case 'speedBoost':
      // 绘制闪电图标
      ctx.strokeStyle = '#fff';
      ctx.lineWidth = 2;
      ctx.beginPath();
      ctx.moveTo(x - radius/3, y - radius/3);
      ctx.lineTo(x + radius/3, y - radius/3);
      ctx.lineTo(x, y + radius/3);
      ctx.stroke();
      break;
      
    case 'doubleScore':
      // 绘制2X图标
      ctx.font = `bold ${radius}px Arial`;
      ctx.fillText('2×', x, y);
      break;
      
    case 'shield':
      // 绘制盾牌图标
      ctx.strokeStyle = '#fff';
      ctx.lineWidth = 2;
      ctx.beginPath();
      ctx.arc(x, y, radius * 0.6, 0, Math.PI * 2);
      ctx.stroke();
      break;
  }
}

// 绘制蛇
function drawSnake(snake, isPlayer) {
  // 根据是玩家还是AI选择不同的颜色
  const headColor = isPlayer ? '#00f7ff' : '#FF3A44';
  const bodyColor = isPlayer ? '#00b3b9' : '#D32F2F';
  
  // 如果玩家有护盾效果
  const hasShield = isPlayer && game.effects.shield;
  
  // 计算蛇身阴影偏移
  const offset = Math.sin(Date.now() / 200) * 3;
  
  // 绘制蛇身
  for (let i = snake.length - 1; i >= 0; i--) {
    const segment = snake[i];
    
    // 蛇头与蛇身不同颜色
    const segmentColor = i === 0 ? headColor : bodyColor;
    
    // 如果有护盾效果，添加蓝色光晕
    if (hasShield) {
      ctx.shadowColor = '#2196F3';
      ctx.shadowBlur = 15;
    } else if (i === 0) {
      // 蛇头有微弱的光晕
      ctx.shadowColor = segmentColor;
      ctx.shadowBlur = 10;
    } else {
      ctx.shadowBlur = 0;
    }
    
    // 绘制圆角矩形
    const x = segment.x * game.gridSize;
    const y = segment.y * game.gridSize;
    const size = game.gridSize - 2;
    const radius = size / 4;
    
    // 渐变填充
    const gradient = ctx.createLinearGradient(x, y, x + size, y + size);
    gradient.addColorStop(0, segmentColor);
    gradient.addColorStop(1, i === 0 ? segmentColor : 'rgba(0,0,0,0.6)');
    
    ctx.fillStyle = gradient;
    
    // 根据位置添加微弱的波动效果
    const xOffset = i === 0 ? 0 : Math.cos((Date.now() / 500) + i * 0.5) * offset;
    const yOffset = i === 0 ? 0 : Math.sin((Date.now() / 500) + i * 0.5) * offset;
    
    ctx.beginPath();
    ctx.moveTo(x + radius + xOffset, y + yOffset);
    ctx.lineTo(x + size - radius + xOffset, y + yOffset);
    ctx.quadraticCurveTo(x + size + xOffset, y + yOffset, x + size + xOffset, y + radius + yOffset);
    ctx.lineTo(x + size + xOffset, y + size - radius + yOffset);
    ctx.quadraticCurveTo(x + size + xOffset, y + size + yOffset, x + size - radius + xOffset, y + size + yOffset);
    ctx.lineTo(x + radius + xOffset, y + size + yOffset);
    ctx.quadraticCurveTo(x + xOffset, y + size + yOffset, x + xOffset, y + size - radius + yOffset);
    ctx.lineTo(x + xOffset, y + radius + yOffset);
    ctx.quadraticCurveTo(x + xOffset, y + yOffset, x + radius + xOffset, y + yOffset);
    ctx.closePath();
    ctx.fill();
    
    // 绘制蛇头眼睛（只对蛇头绘制）
    if (i === 0) {
      ctx.fillStyle = '#fff';
      
      // 根据蛇的方向确定眼睛位置
      const direction = isPlayer ? game.direction : game.aiDirection;
      let eyeX1, eyeY1, eyeX2, eyeY2;
      const eyeSize = game.gridSize / 6;
      const eyeOffset = game.gridSize / 4;
      
      switch(direction) {
        case 'up':
          eyeX1 = x + eyeOffset;
          eyeY1 = y + eyeOffset;
          eyeX2 = x + size - eyeOffset;
          eyeY2 = y + eyeOffset;
          break;
        case 'down':
          eyeX1 = x + eyeOffset;
          eyeY1 = y + size - eyeOffset;
          eyeX2 = x + size - eyeOffset;
          eyeY2 = y + size - eyeOffset;
          break;
        case 'left':
          eyeX1 = x + eyeOffset;
          eyeY1 = y + eyeOffset;
          eyeX2 = x + eyeOffset;
          eyeY2 = y + size - eyeOffset;
          break;
        case 'right':
          eyeX1 = x + size - eyeOffset;
          eyeY1 = y + eyeOffset;
          eyeX2 = x + size - eyeOffset;
          eyeY2 = y + size - eyeOffset;
          break;
      }
      
      // 绘制眼睛
      ctx.beginPath();
      ctx.arc(eyeX1, eyeY1, eyeSize, 0, Math.PI * 2);
      ctx.fill();
      
      ctx.beginPath();
      ctx.arc(eyeX2, eyeY2, eyeSize, 0, Math.PI * 2);
      ctx.fill();
      
      // 绘制瞳孔（眨眼动画）
      const blinkFactor = Math.sin(Date.now() / 2000) > 0.95 ? 0 : 1;
      
      ctx.fillStyle = isPlayer ? '#000814' : '#000';
      
      if (blinkFactor > 0) {
        ctx.beginPath();
        ctx.arc(eyeX1, eyeY1, eyeSize / 2, 0, Math.PI * 2);
        ctx.fill();
        
        ctx.beginPath();
        ctx.arc(eyeX2, eyeY2, eyeSize / 2, 0, Math.PI * 2);
        ctx.fill();
      }
    }
  }
  
  // 重置阴影
  ctx.shadowColor = 'transparent';
  ctx.shadowBlur = 0;
}

// 游戏结束
function gameOver() {
  game.isRunning = false;
  
  // 取消所有动画帧请求
  if (game.animationFrameId) {
    cancelAnimationFrame(game.animationFrameId);
    game.animationFrameId = null;
  }
  
  // 播放游戏结束音效
  playSound('gameOver');
  
  // 屏幕振动效果
  shakeScreen();
  
  // 更新最高分
  if (game.score > game.highScore) {
    game.highScore = game.score;
    // 储存最高分
    localStorage.setItem('snakeHighScore', game.highScore);
  }
  
  // 更新结算界面内容
  document.getElementById('finalScore').textContent = game.score;
  document.getElementById('finalLength').textContent = game.snake.length;
  document.getElementById('finalHighScore').textContent = game.highScore;
  document.getElementById('finalTime').textContent = `${Math.floor(game.gameTime)}秒`;
  
  // 根据游戏模式设置界面样式
  const modal = document.getElementById('gameOverModal');
  
  // 设置模式标签
  const modeBadge = document.getElementById('modeBadge');
  
  if (game.aiMode) {
    modeBadge.textContent = 'AI对战';
    modeBadge.style.background = '#FF3A44';
    
    // 显示AI数据
    document.getElementById('aiStatsContainer').style.display = 'flex';
    document.getElementById('aiLengthContainer').style.display = 'flex';
    document.getElementById('finalAiScore').textContent = game.aiScore;
    document.getElementById('finalAiLength').textContent = game.aiSnake.length;
    
    // 确定胜负
    const result = game.score > game.aiScore ? '你赢了！' : (game.score < game.aiScore ? 'AI赢了！' : '平局！');
    document.querySelector('.modal-title').textContent = result;
  } else if (game.obstacleMode) {
    modeBadge.textContent = '障碍模式';
    modeBadge.style.background = '#795548';
    
    // 隐藏AI数据
    document.getElementById('aiStatsContainer').style.display = 'none';
    document.getElementById('aiLengthContainer').style.display = 'none';
    
    document.querySelector('.modal-title').textContent = '任务结束';
  } else {
    modeBadge.textContent = '标准模式';
    modeBadge.style.background = '#00f7ff';
    
    // 隐藏AI数据
    document.getElementById('aiStatsContainer').style.display = 'none';
    document.getElementById('aiLengthContainer').style.display = 'none';
    
    document.querySelector('.modal-title').textContent = '任务结束';
  }
  
  // 显示结算界面
  setTimeout(() => {
    modal.style.display = 'flex';
    createModalParticles();
  }, 1000);
  
  // 为结算界面按钮添加事件监听
  document.getElementById('modalRestartBtn').addEventListener('click', function() {
    modal.style.display = 'none';
    initGame();
    startGame();
  });
  
  document.getElementById('modalMenuBtn').addEventListener('click', function() {
    modal.style.display = 'none';
    initGame();
  });
  
  document.getElementById('modalShareBtn').addEventListener('click', shareScore);
}

// 屏幕振动效果
function shakeScreen() {
  const gameContainer = document.querySelector('.game-container');
  gameContainer.classList.add('shake');
  setTimeout(() => {
    gameContainer.classList.remove('shake');
  }, 500);
}

// 创建结算界面粒子
function createModalParticles() {
  const particlesContainer = document.getElementById('modalParticles');
  particlesContainer.innerHTML = '';
  
  for (let i = 0; i < 30; i++) {
    const particle = document.createElement('div');
    particle.className = 'modal-particle';
    
    // 随机位置和属性
    const size = Math.random() * 8 + 2;
    particle.style.width = `${size}px`;
    particle.style.height = `${size}px`;
    particle.style.left = `${Math.random() * 100}%`;
    particle.style.top = `${Math.random() * 100}%`;
    
    // 随机颜色
    const hue = Math.random() > 0.5 ? 183 : 348; // 蓝色或红色
    particle.style.backgroundColor = `hsl(${hue}, 100%, 65%)`;
    
    // 随机动画延迟
    particle.style.animationDelay = `${Math.random() * 2}s`;
    
    particlesContainer.appendChild(particle);
  }
}

// 分享分数
function shareScore() {
  let shareText = `我在科技蛇游戏中获得了 ${game.score} 分，长度达到了 ${game.snake.length}！`;
  
  if (game.obstacleMode) {
    shareText += '（障碍模式）';
  }
  
  if (game.aiMode) {
    const result = game.score > game.aiScore ? '战胜了AI！' : (game.score < game.aiScore ? '被AI击败了。' : '与AI打成了平手！');
    shareText += `在AI对战中${result}`;
  }
  
  // 尝试使用分享API
  if (navigator.share) {
    navigator.share({
      title: '科技蛇游戏成绩',
      text: shareText
    }).catch(err => {
      console.error('分享失败:', err);
      copyToClipboard(shareText);
    });
  } else {
    // 复制到剪贴板
    copyToClipboard(shareText);
  }
}

// 复制文本到剪贴板
function copyToClipboard(text) {
  if (navigator.clipboard) {
    navigator.clipboard.writeText(text)
      .then(() => alert('分享文本已复制到剪贴板！'))
      .catch(err => {
        console.error('复制失败:', err);
        alert(text);
      });
  } else {
    alert(text);
  }
}

// 按键控制（保留键盘控制支持）
document.addEventListener('keydown', function(e) {
  if (!game.isRunning) return;
  
  // 阻止方向键的默认行为（页面滚动）
  if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'w', 'a', 's', 'd', 'W', 'A', 'S', 'D', ' '].includes(e.key)) {
    e.preventDefault();
  }
  
  // 暂停控制
  if (e.key === ' ') {
    togglePause();
    return;
  }
  
  if (game.isPaused) return;
  
  // 方向控制 - 支持方向键和WASD
  switch(e.key) {
    case 'ArrowUp':
    case 'w':
    case 'W':
      if (game.direction !== 'down') game.direction = 'up';
      break;
    case 'ArrowDown':
    case 's':
    case 'S':
      if (game.direction !== 'up') game.direction = 'down';
      break;
    case 'ArrowLeft':
    case 'a':
    case 'A':
      if (game.direction !== 'right') game.direction = 'left';
      break;
    case 'ArrowRight':
    case 'd':
    case 'D':
      if (game.direction !== 'left') game.direction = 'right';
      break;
  }
});

    </script>
    
    <!-- 确保资源加载完成后隐藏加载屏幕 -->
    <script>
        window.addEventListener('load', function() {
            // 延迟一小段时间确保所有资源加载完成
            setTimeout(function() {
                document.getElementById('loadingScreen').style.opacity = '0';
                setTimeout(function() {
                    document.getElementById('loadingScreen').style.display = 'none';
                }, 500);
            }, 500);
        });
    </script>
</body>
</html>
